package com.pig4cloud.pig.module.controller.property;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.location.City;
import com.pig4cloud.pig.module.api.entity.location.District;
import com.pig4cloud.pig.module.api.entity.location.Province;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.service.location.CityService;
import com.pig4cloud.pig.module.service.location.DistrictService;
import com.pig4cloud.pig.module.service.location.ProvinceService;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 物业公司Controller
 *
 * @author ruoyi
 * @date 2021-08-24
 */
@Validated
@Api(value = "物业公司控制器", tags = {"物业公司管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/property")
public class PropertyController {

    private final IPropertyService propertyService;

	private final ProvinceService provinceService;

	private final CityService cityService;

	private final DistrictService districtService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询物业公司列表
     */
    @ApiOperation("查询物业公司列表")
	@PreAuthorize("@pms.hasPermission('module:property:list')")
    @GetMapping("/list")
    public TableDataInfo<Property> list(@Validated Property property) {
		QueryWrapper<Property> qw = new QueryWrapper<>();
		if(StrUtil.isNotEmpty(property.getPropertyName())){
			qw.like("property_ame",property.getPropertyName());
		}
		TableDataInfo<Property> td = PageUtils.buildDataInfo(propertyService.page(PageUtils.buildPage(),qw));
		List<Property> list = td.getData();
		list.forEach(property1 -> {
			if(StrUtil.isNotEmpty(property1.getLogoUrl())){
				if(StrUtil.isNotEmpty(property1.getLogoUrl()) && property1.getLogoUrl().indexOf("http") < 0){
					property1.setLogoUrlPath(imgUrl + property1.getLogoUrl());
				}else{
					property1.setLogoUrlPath(property1.getLogoUrl());
				}
			}else{
				property1.setLogoUrlPath("");
			}
		});
        return td;
    }


	/**
	 * 查询物业公司列表
	 */
	@ApiOperation("查询物业公司列表")
	@GetMapping("/listNoPage")
	public R<List<Property>> listNoPage(@Validated Property property) {
//		PigUser sysUser = SecurityUtils.getUser();
		QueryWrapper<Property> qw = new QueryWrapper<>();
		qw.eq("state",0);
		List<Property> list = propertyService.list(qw);
		return R.ok(list);
	}

    /**
     * 获取物业公司详细信息
     */
    @ApiOperation("获取物业公司详细信息")
	@PreAuthorize("@pms.hasPermission('module:property:query')")
    @GetMapping("/{id}")
    public R<Property> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Property property = propertyService.getById(id);
        if(property!=null){
			if(StrUtil.isNotEmpty(property.getLogoUrl())){
				if(StrUtil.isNotEmpty(property.getLogoUrl()) && property.getLogoUrl().indexOf("http") < 0){
					property.setLogoUrlPath(imgUrl + property.getLogoUrl());
				}else{
					property.setLogoUrlPath(property.getLogoUrl());
				}
			}else{
				property.setLogoUrlPath("");
			}

//			if(property.getProvId()!=null && property.getCityId()!=null){
//				String[] areas = { property.getProvId() + "", property.getCityId()+""};
//				property.setProvinceArray(areas);
//			}

			if(StrUtil.isNotEmpty(property.getAreaOptions())){
				String areaOptions = property.getAreaOptions();
//                List<String> list = Arrays.asList(areaOptions.split(","));
//                System.out.println(list);
				property.setProvinceArray(areaOptions.split(","));
			}
		}
        return R.ok(property);
    }

    /**
     * 新增物业公司
     */
    @ApiOperation("新增物业公司")
    @SysLog("物业公司")

	@PreAuthorize("@pms.hasPermission('module:property:add')")
    @PostMapping()
    public R<Void> add(@Valid @RequestBody Property property) {
		String[] list = property.getProvinceArray();
		if (list != null) {
			String str = StringUtils.join(list, ",");
			System.out.println(str + "======");
			if (list.length > 0) {
				Province province = provinceService.findById(list[0]);
				if (province != null) {
					property.setProv(province.getProvinceName());
					property.setProvId(province.getId());
					property.setCity(null);
					property.setDistrict(null);
				}
				if (list.length > 1) {
					City city = cityService.getById(list[1]);
					if (city != null) {
						property.setCity(city.getCityName());
						property.setCityId(city.getId());
						property.setDistrict(null);
					}
				}
				if (list.length > 2) {
					District district = districtService.findById(list[2]);
					if (district != null) {
						property.setDistrict(district.getDistrictName());
					}
				}
				property.setAreaOptions(str);
			}
		}
		return R.okByRow(propertyService.save(property) ? 1 : 0);
	}

	/**
	 * 修改物业公司
	 */
	@ApiOperation("修改物业公司")
	@PreAuthorize("@pms.hasPermission('module:property:edit')")
	@SysLog("物业公司")

	@PutMapping()
    public R<Void> edit(@Valid @RequestBody Property property) {
		String[] list = property.getProvinceArray();
		if(list!=null){
			String str = StringUtils.join(list,",");
			System.out.println(str+"======");
			if (list.length > 0) {
				Province province = provinceService.findById(list[0]);
				if (province != null) {
					property.setProv(province.getProvinceName());
					property.setProvId(province.getId());
					property.setCity(null);
					property.setDistrict(null);
				}
				if (list.length > 1) {
					City city = cityService.getById(list[1]);
					if (city != null) {
						property.setCity(city.getCityName());
						property.setCityId(city.getId());
						property.setDistrict(null);
					}
				}
				if (list.length > 2) {
					District district = districtService.findById(list[2]);
					if (district != null) {
						property.setDistrict(district.getDistrictName());
					}
				}
			}
			property.setAreaOptions(str);
		}
        return R.okByRow(propertyService.updateById(property) ? 1 : 0);
    }

    /**
     * 删除物业公司
     */
    @ApiOperation("删除物业公司")
    @SysLog("物业公司")
	@PreAuthorize("@pms.hasPermission('module:property:remove')")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(propertyService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
